/*
 * BorderLayoutDemo.java is a 1.4 application that requires no other files.
 */
package webOffline;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import myFileUtils.*;

public class WebOffline implements ActionListener, 
                                   TreeSelectionListener,
                                   TreeModelListener,
                                   PropertyChangeListener
{
    public static boolean RIGHT_TO_LEFT = false;
    static final private String START = "startBtn";
    static final private String PAUSE = "pauseBtn";
    static final private String STOP = "stopBtn";
    static final private String NEW_BTN = "newBtn";
    static final private String ABOUT = "aboutMenu";
    static final private String HELP = "helpMenu";
    static final private String QUIT = "quitMenu";
    static final private String OPTION = "optionMenu";
    static final private String NEW_MENU = "newMenu";
    static final private String OPEN = "openMenu";
    static final private String SAVE = "saveMenu";
    static final public String resourcesPath = "Resources/";
    static final public String imagesPath = "Resources/images/";
    static final public String projectsPath = "Resources/Projects/";
    private ArrayList <ProjectDownloadManager> arrayProjects;
    private JFrame frame;
    private Container pane;
    private JButton startBtn,
            pauseBtn,
            stopBtn,
            newBtn;
    private JLabel runningLabel,
            statusLabel;
    private JTree tree;
    private JTable containTable;
    private DefaultTableModel containTableModel;
    private DefaultMutableTreeNode topTreeNode;
    private DefaultTreeModel treeModel;
    private Toolkit toolkit = Toolkit.getDefaultToolkit();
    private ArrayList <RequestPages> arrayRequestPages;
//    private ArrayList <String> listFolderPath = new ArrayList<String>();
    private ArrayList <LoadFile> arrayLoadFile = new ArrayList<LoadFile>();

    Object[][] data = {{"1","",""},{"2","",""},{"3","",""},{"4","",""},{"5","",""},
                        {"6","",""},{"7","",""},{"8","",""},{"9","",""},{"10","",""}};
    private MyTableModel model;



    private void addButtonsToolbar(JToolBar toolBar) {
        newBtn = makeNavigationButton("newIcon", NEW_BTN,
                                      "New Project Wizard",
                                      "New");
        toolBar.add(newBtn);
        //separator
        toolBar.addSeparator();

        //first button
        startBtn = makeNavigationButton("startIcon", START,
                                      "Start getting web",
                                      "Start");
        startBtn.setEnabled(false);
        toolBar.add(startBtn);

        //second button
        pauseBtn = makeNavigationButton("pauseIcon", PAUSE,
                                      "Pause getting web",
                                      "Pause");
        pauseBtn.setEnabled(false);
        toolBar.add(pauseBtn);

        //third button
        stopBtn = makeNavigationButton("stopIcon", STOP,
                                      "Stop getting Web",
                                      "Stop");
        stopBtn.setEnabled(false);
        toolBar.add(stopBtn);

        //separator
        toolBar.addSeparator();

        ImageIcon icon = new ImageIcon(imagesPath + "runningIcon.png");
        runningLabel = new JLabel("");
        runningLabel.addPropertyChangeListener(this);

        toolBar.add(runningLabel);
    }

    private JButton makeNavigationButton(String imageName,
                                           String actionCommand,
                                           String toolTipText,
                                           String altText) {
        //Look for the image.
        ImageIcon icon = new ImageIcon(imagesPath
                                        + imageName
                                        + ".png");
        

        JButton button = new JButton(icon);
        button.setActionCommand(actionCommand);
        button.setToolTipText(toolTipText);
        button.addActionListener(this);

        return button;
    }
    
    private JPanel createPageStartPane() {
        JPanel paneStartPane = new JPanel(new BorderLayout());
        paneStartPane.setBorder(BorderFactory.createLineBorder(Color.lightGray, 2));

        JToolBar toolBar = new JToolBar("Still draggable");
        addButtonsToolbar(toolBar);
        //toolBar.setFloatable(false);
        toolBar.setRollover(true);
      
        paneStartPane.add(toolBar, BorderLayout.PAGE_START);

        return paneStartPane;
    }
    
    private JPanel createCenterPane() {
        JPanel centerPane = new JPanel(new BorderLayout());

        topTreeNode = new DefaultMutableTreeNode("PROJECTS");
        treeModel = new DefaultTreeModel(topTreeNode);
	treeModel.addTreeModelListener(this);
        tree = new JTree(treeModel);
        tree.setEditable(true);
        tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        tree.setShowsRootHandles(true);

        tree.setPreferredSize(new Dimension(350, 500));
        tree.setBorder(BorderFactory.createLineBorder(Color.lightGray, 1));
        tree.setScrollsOnExpand(true);
        tree.addTreeSelectionListener(this);


        JScrollPane pane1 = new JScrollPane(tree,  JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        tree.setAutoscrolls(true);
        ImageIcon icon = new ImageIcon (imagesPath + "/projectIcon.png");
        DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
        renderer.setLeafIcon(icon);
        tree.setCellRenderer(renderer);


        String [] columnName = new String []{"No", "Name", "Size"};
//        containTableModel = new DefaultTableModel(data,columnName);
        containTable = new JTable(containTableModel){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }};
        containTable.setFillsViewportHeight(true);
        containTable.setPreferredScrollableViewportSize(new Dimension(100, 100));
        
        model = new MyTableModel(columnName);

        containTable.setModel(model);
        containTable.setDefaultRenderer(JLabel.class, new MyRenderer());

        TableColumn column = null;

        for (int i = 0; i < 2; i++) {
            column = containTable.getColumnModel().getColumn(i);
            if (i == 0) {
                column.setPreferredWidth(30);
            }
            else if(i == 1) {
                column.setPreferredWidth(400);
            }
            else {
                column.setPreferredWidth(15);
            }
        }

        JScrollPane pane2 = new JScrollPane(containTable);

        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,pane1,pane2);
        splitPane.setOneTouchExpandable(true);
        splitPane.setDividerLocation(240);

        Dimension minimumSize = new Dimension(200, 100);
        pane1.setMinimumSize(minimumSize);
        pane2.setMinimumSize(minimumSize);

        centerPane.add(splitPane,BorderLayout.CENTER);

//        insertBlankRows(30);

        return centerPane;
    }

    private JPanel createPageEndPane() {
        JPanel panePageEndPane = new JPanel();
        statusLabel = new JLabel("Project saved");
        panePageEndPane.add(statusLabel);

        return panePageEndPane;
    }

    private JMenuBar createMenuBar() {
        JMenuBar menuBar = new JMenuBar();

        //Menu Files
        JMenu menu = new JMenu("File");
        menu.setMnemonic(KeyEvent.VK_F);
        menu.getAccessibleContext().setAccessibleDescription("All tools of Application");
        menuBar.add(menu);

        //MenuItems: Files -> Changes Attribute
        ImageIcon icon1 = new ImageIcon(imagesPath + "newproject.png");
        JMenuItem menuItem = new JMenuItem("Project Wizard    ",icon1);
        //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
        menuItem.setAccelerator(KeyStroke.getKeyStroke(
                KeyEvent.VK_N, ActionEvent.CTRL_MASK));
        menuItem.getAccessibleContext().setAccessibleDescription(
                "New Project Winzard");
        menuItem.addActionListener(this);
        menuItem.setEnabled(true);
        menuItem.setActionCommand(NEW_MENU);
        menuItem.setName("newProjectMenu");
        menu.add(menuItem);

        ImageIcon icon5 = new ImageIcon(imagesPath + "openIcon.png");
        menuItem = new JMenuItem("Open Project    ",icon5);
        //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
        menuItem.setAccelerator(KeyStroke.getKeyStroke(
                KeyEvent.VK_O, ActionEvent.CTRL_MASK));
        menuItem.getAccessibleContext().setAccessibleDescription(
                "Open Project");
        menuItem.addActionListener(this);
        menuItem.setEnabled(true);
        menuItem.setActionCommand(OPEN);
        menuItem.setName(OPEN);
        menu.add(menuItem);

         //ImageIcon icon5 = new ImageIcon(imagesPath + "saveIcon.png");
        menuItem = new JMenuItem("Save Project    ",icon5);
        //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
        menuItem.setAccelerator(KeyStroke.getKeyStroke(
                KeyEvent.VK_S, ActionEvent.CTRL_MASK));
        menuItem.getAccessibleContext().setAccessibleDescription(
                "Save Project");
        menuItem.addActionListener(this);
        menuItem.setEnabled(true);
        menuItem.setActionCommand(SAVE);
        menuItem.setName(SAVE);
        menu.add(menuItem);

        ImageIcon icon2 = new ImageIcon(imagesPath + "optionIcon.png");
        menuItem = new JMenuItem("Option",icon2);
        //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
        menuItem.setAccelerator(KeyStroke.getKeyStroke(
                KeyEvent.VK_P, ActionEvent.CTRL_MASK));
        menuItem.getAccessibleContext().setAccessibleDescription(
                "Project Options");
        menuItem.addActionListener(this);
        menuItem.setEnabled(true);
        menuItem.setActionCommand(OPTION);
        menuItem.setName(OPTION);
        menu.add(menuItem);
        menu.insertSeparator(2);

        ImageIcon icon3 = new ImageIcon(imagesPath + "quitIcon.png");
        menuItem = new JMenuItem("Quit",icon3);
        menuItem.setAccelerator(KeyStroke.getKeyStroke(
                KeyEvent.VK_F4, ActionEvent.ALT_MASK));
        menuItem.setMnemonic(KeyEvent.VK_F4);
        menuItem.addActionListener(this);
        menuItem.setName(QUIT);
        menuItem.setActionCommand(QUIT);
        menu.add(menuItem);

        menu = new JMenu("?");
        menu.setMnemonic(KeyEvent.VK_H);
        menu.getAccessibleContext().setAccessibleDescription(
                "About");

        ImageIcon icon6 = new ImageIcon(imagesPath + "helpIcon.png");
        menuItem = new JMenuItem("Help", icon6);
        menuItem.setName(HELP);
        menuItem.setActionCommand(HELP);
        menuItem.setAccelerator(KeyStroke.getKeyStroke("F1"));
        menuItem.setMnemonic(KeyEvent.VK_F1);
        menuItem.addActionListener(this);
        menu.add(menuItem);

        ImageIcon icon4 = new ImageIcon(imagesPath + "infoIcon.png");
        menuItem = new JMenuItem("About",icon4);
        menuItem.setName(ABOUT);
        menuItem.setActionCommand(ABOUT);
        menuItem.setAccelerator(KeyStroke.getKeyStroke(
                KeyEvent.VK_B, ActionEvent.CTRL_MASK));
        menuItem.setMnemonic(KeyEvent.VK_B);
        menuItem.addActionListener(this);
        menu.add(menuItem);

        menuBar.add(menu);

        return menuBar;
    }

    private Container addComponentsToPane() {
        pane = frame.getContentPane();
        if (!(pane.getLayout() instanceof BorderLayout)) {
            pane.add(new JLabel("Container doesn't use BorderLayout!"));

            return null;
        }

        if (RIGHT_TO_LEFT) {
            pane.setComponentOrientation(
                java.awt.ComponentOrientation.RIGHT_TO_LEFT);
        }

        pane.add(createPageStartPane(), BorderLayout.PAGE_START);

        pane.add(createCenterPane(), BorderLayout.CENTER);
        pane.add(createPageEndPane(), BorderLayout.PAGE_END);

        return pane;
    }

//    private void insertBlankRows(int numRow) {
//        if(numRow > 0) {
//            int rowCount = containTableModel.getRowCount();
//            for(int i = 0; i < numRow; i++) {
//                String []rowData = new String[]{String.valueOf(rowCount + i + 1),"",""};
//                containTableModel.insertRow(rowCount + i, rowData);
//            }
//        }
//    }

    private void openProject () throws Exception {
        JFileChooser fci = new JFileChooser();
        FileNameExtensionFilter filter1 = new FileNameExtensionFilter("XML Document", "xml");
        fci.setFileFilter(filter1);

        int returnVal = fci.showOpenDialog(frame);
        String folder = "";

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fci.getSelectedFile();
            folder = file.getCanonicalPath();

            ProjectDownloadManager pdm = DOMXml.openProject(folder);

            // save project after construction
            String saveDir = pdm.getProjectAddress().getSaveTo();
            String name = pdm.getProjectAddress().getProjectName();

            file = new File (saveDir + name);
            if (!file.exists()) {
                file.mkdirs();
            }

            DOMXml.saveProject(pdm, saveDir + name + ".xml");
            arrayProjects.add(pdm);
            addObject(null, pdm.getTopNode());

            RequestPages req = new RequestPages(pdm,
                                                "",
                                                pdm.getProjectAddress().getProjectName());
            arrayRequestPages.add(req);
            req.thread.start();
        }
    }

    private boolean saveProject (String path) {
        return true;
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();
        
        if(cmd.equals(NEW_BTN) || cmd.equals(NEW_MENU)) {
            ProjectWizard pw = new ProjectWizard();
            pw.createAndShowGUI();
            
            if(pw.getResultDialog()) {
                ProjectDownloadManager pdm = null;
                try {
                    pdm = new ProjectDownloadManager(pw.getProjectAddress());
                } catch (Exception ex) {
                    Logger.getLogger(WebOffline.class.getName()).log(Level.SEVERE, null, ex);
                }

                // save project after construction
                String saveDir = pdm.getProjectAddress().getSaveTo();
                String name = pdm.getProjectAddress().getProjectName();
                File file = new File (saveDir + name);
                if (!file.exists()) {
                    file.mkdirs();
                }
                
                DOMXml.saveProject(pdm, saveDir + name + ".xml");
                arrayProjects.add(pdm);
                addObject(null, pdm.getTopNode());

                // downloading
                RequestPages req = new RequestPages(pdm, 
                                                    "",
                                                    pdm.getProjectAddress().getProjectName());
                arrayRequestPages.add(req);
                req.thread.start();

//                suppendAllLoadFileThread();
//                LoadFile loading = new LoadFile(pdm.getProjectAddress().getSaveTo(),
//                                                containTable,
//                                                model);
//                arrayLoadFile.add(loading);

                // list all link in project.
                // show message box and starting download after confirm
            }
        }
        else if(cmd.equals(START)) {
            // 1. get project is forcussing
            // 2. get index of project
            // 3. check state of

        }
        else if(cmd.equals(PAUSE)) {

        }
        else if(cmd.equals(STOP)) {

        }
        else if(cmd.equals(OPTION)) {
            Option opt = new Option();
            opt.createAndShowGUI();
        }
        else if(cmd.equals(OPEN)) {
            try {
                openProject();
            } catch (Exception ex) {
                Logger.getLogger(WebOffline.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        else if(cmd.equals(SAVE)) {
            
            JOptionPane.showMessageDialog(pane, "Project Saved!");
        }
        else if(cmd.equals(QUIT)) {
            int res = JOptionPane.showConfirmDialog(
                    pane,
                    "Do you really want to quit?", "Question",
                    JOptionPane.YES_NO_OPTION);
            
            if(res == JOptionPane.YES_OPTION) {
                System.exit(0);
            }
        }
        else if(cmd.equals(ABOUT)) {
           About about = new About();
           about.createAndShowGUI("About WebOffline", true);
        }
        else if (cmd.equals(HELP)) {
            openHelpFile();
        }
//        else if (cmd.equals("Load File")) {
//            loadFile("D:/[DOWNLOADS]", model);
//        }
//        else if (cmd.equals("Test")) {
//            JOptionPane.showMessageDialog(pane, check.getText());
//        }

    }

    private void openHelpFile() {
        String command = "";
        String pathFilename = "Resources\\Help\\Help.doc";

        File root = new File(".");
        File file = new File(root + "\\" + pathFilename);

        if(!file.exists()) {
            System.out.println("Could not file file \\Resources\\Help\\Help.doc");
            JOptionPane.showMessageDialog(null, "Could not file file \\Resources\\Help\\Help.doc");
        }

        command = "cmd.exe /c " + file;

        try {
            Runtime rt = Runtime.getRuntime();
            //Process pr = rt.exec("cmd /c dir");

            Process pr = rt.exec(command);

            BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));

            String line = null;

            while((line=input.readLine()) != null) {
                System.out.println(line);
            }

            int exitVal = pr.waitFor();

            System.out.println("Exited with error code " + exitVal);
        } catch(Exception e) {
            System.out.println(e.toString());
        }
    }

    private int findPrject (String projectName) {
        int sum = arrayProjects.size();
        for (int idx = 0; idx < sum; ++idx) {
            if (arrayProjects.get(idx).getProjectAddress().getProjectName().equals(projectName)) {
                return idx;
            }
        }
        return -1;
    }

    private String getProjectName(String treePath) {
        int idx = treePath.lastIndexOf(',');
        return treePath.substring(idx + 2, treePath.length() -1);
    }

    

    @Override
    public void valueChanged(TreeSelectionEvent e) {
        // 1. get project selection
        String rootTree = "[PROJECTS]";
        String path = e.getPath().toString();
        
        if (!rootTree.equals(path)) {
            System.out.println (e.getPath().toString());

            String projectName = getProjectName (path);
            int projectIndex = findPrject(projectName);

            String addressDir = arrayProjects.get(projectIndex).getProjectAddress().getSaveTo();
            blankTable(model);
            loadFile(addressDir, 1);
        }
    }

    public void createAndShowGUI() {
        try {
           UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        }catch (Exception ec) {
            JOptionPane.showMessageDialog(pane, ec.getMessage());
        }

        //Create and set up the window.
        frame = new JFrame("WebOffline");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Set up the content pane.
        frame.setContentPane(addComponentsToPane());
        frame.setPreferredSize(new Dimension(800, 600));
        frame.setJMenuBar(createMenuBar());
        frame.setIconImage(Toolkit.getDefaultToolkit().getImage(imagesPath + "mainIcon.png"));

        //Display the window.
        frame.pack();
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);

        arrayProjects = new ArrayList<ProjectDownloadManager>();
        arrayRequestPages = new ArrayList<RequestPages>();
    }

    /** Remove all nodes except the root node. */
    public void clear() {
        topTreeNode.removeAllChildren();
        treeModel.reload();
    }

    /** Remove the currently selected node. */
    public void removeCurrentNode() {
        TreePath currentSelection = tree.getSelectionPath();

        if (currentSelection != null) {
            DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)
                         (currentSelection.getLastPathComponent());
            MutableTreeNode parent = (MutableTreeNode)(currentNode.getParent());

            if (parent != null) {
                treeModel.removeNodeFromParent(currentNode);
                return;
            }
        }

        // Either there was no selection, or the root was selected.
        toolkit.beep();
    }

    /** Add child to the currently selected node. */
    public DefaultMutableTreeNode addObject(Object child) {
        DefaultMutableTreeNode parentNode = null;
        TreePath parentPath = tree.getSelectionPath();

        if (parentPath == null) {
            parentNode = topTreeNode;
        } else {
            parentNode = (DefaultMutableTreeNode)
                         (parentPath.getLastPathComponent());
        }

        return addObject(parentNode, child, true);
    }

    public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
                                            Object child) {
        return addObject(parent, child, false);
    }

    public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
                                            Object child,
                                            boolean shouldBeVisible) {
        DefaultMutableTreeNode childNode =
                new DefaultMutableTreeNode(child);

        if (parent == null) {
            parent = topTreeNode;
        }
        

	//It is key to invoke this on the TreeModel, and NOT DefaultMutableTreeNode
        treeModel.insertNodeInto(childNode, parent,
                                 parent.getChildCount());

        //Make sure the user can see the lovely new node.
        if (shouldBeVisible) {
            tree.scrollPathToVisible(new TreePath(childNode.getPath()));
        }
        
        return childNode;
    }

    @Override
    public void treeNodesChanged(TreeModelEvent e) {
        DefaultMutableTreeNode node;
        node = (DefaultMutableTreeNode)(e.getTreePath().getLastPathComponent());

        /*
         * If the event lists children, then the changed
         * node is the child of the node we've already
         * gotten.  Otherwise, the changed node and the
         * specified node are the same.
         */

        int index = e.getChildIndices()[0];
        node = (DefaultMutableTreeNode)(node.getChildAt(index));
    }

    @Override
    public void treeNodesInserted(TreeModelEvent e) {
//        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void treeNodesRemoved(TreeModelEvent e) {
//        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void treeStructureChanged(TreeModelEvent e) {
//        throw new UnsupportedOperationException("Not supported yet.");
    }

    private void blankTable (MyTableModel model) {
        String [] columnName = new String []{"No", "Name", "Size (B)"};

        Object [][] vectorData = null;
        model.setDataVector(vectorData, columnName);
        containTable.setModel(model);
        containTable.setDefaultRenderer(JLabel.class, new MyRenderer());

        TableColumn column = null;

        for (int i = 0; i < 2; i++) {
            column = containTable.getColumnModel().getColumn(i);
            if (i == 0) {
                column.setPreferredWidth(30);
            }
            else if(i == 1) {
                column.setPreferredWidth(400);
            }
            else {
                column.setPreferredWidth(15);
            }
        }
    }

    public void suppendAllLoadFileThread () {
        int sumOfProject = arrayLoadFile.size();
        for (int idx = 0; idx < sumOfProject; ++idx) {
            arrayLoadFile.get(idx).suppendLoadFile();
        }
    }

    private void loadFile (String folderName, int orderNumber) {
        try {
            File file = new File(folderName);
            if(!file.canRead()){
                // JOptionPane.showMessageDialog(null, "Drive not found!");
                System.err.println ("Drive not found!");
            }

            File []listOfFile = file.listFiles();
            if (listOfFile != null) {
                Arrays.sort(listOfFile);

                String name; //, ext, size, date;
                ImageIcon icon = new ImageIcon();

                for (int i = 0; i < listOfFile.length; i++){
                    if (listOfFile[i].isFile()){
                        name = listOfFile[i].getName();

                        sun.awt.shell.ShellFolder sf = sun.awt.shell.ShellFolder.getShellFolder(listOfFile[i]);
                        icon = new ImageIcon(sf.getIcon(true).getScaledInstance(16, 14, 0));


                        Object []row = {orderNumber,
                                        new JLabel(name, icon, SwingConstants.LEFT),
                                        listOfFile [i].length()};
                        model.addRow(row);
                        ++ orderNumber;
                    }
                    else if (listOfFile[i].isDirectory()) {
                        loadFile(listOfFile [i].getCanonicalPath(), orderNumber);
                    }
                }
            }
        }catch(Exception ex){
            System.err.println (ex);
            //JOptionPane.showMessageDialog(null, "Sorry, I can't open this folder");
            System.err.println ("Sorry, I can't open this folder");
        }
    }

    private ArrayList <String> getListFolderPath(String filePath){
        ArrayList <String> listFolderPath = new ArrayList<String>();
        try {
            File file = new File(filePath);
            if(file.isDirectory() == false){
                System.out.println("Đường dẫn phải là Folder");
//                return;
            }

           File []listFile = file.listFiles();
           for(int i = 0; i < listFile.length; i++){
               if(listFile[i].isDirectory() == true){
                   listFolderPath.add(listFile[i].getPath());
                   getListFolderPath(listFile[i].getPath());
               }
           }
        } catch (Exception ex){
            System.err.println (ex);
        }

        return listFolderPath;
    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        //throw new UnsupportedOperationException("Not supported yet.");
        System.out.println ("PropertyChangeListener");
    }


}
